﻿using System;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace netCoreStudy.Helper
{
	/// <summary>
	/// appSettings.json 操作类
	/// </summary>
	public class AppSettingHelper
	{
		static IConfiguration Configuration { get; set; }

		public AppSettingHelper(string contentPath)
		{
			string path = "appsettings.json";
			Configuration = new ConfigurationBuilder()
				.SetBasePath(contentPath)
				.Add(
					new JsonConfigurationSource()
					{
						//可以直接读取的json文件
						//而不是bin目录下的
						//所以不用修改复制属性
						Path = path,
						Optional = false,
						ReloadOnChange = true
					}
				)
				.Build();
		}

		public AppSettingHelper(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		/// <summary>
		/// 封装要操作的字符
		/// </summary>
		/// <param name="sections">节点配置</param>
		/// <returns></returns>
		public static string app(params string[] sections)
		{
			try
			{
				if (sections.Any())
				{
					return Configuration[string.Join(":", sections)];
				}
			}
			catch (Exception)
			{
				// ignored
			}

			return "";
		}

		public static T GetWholeObj<T>(string key)
		{
			T wholeObj = Configuration.GetSection(key).Get<T>();

			if (wholeObj == null)
				throw new Exception($"配置文件里面没有{key}这个字段");

			return wholeObj;
		}
	}
}